import json
from flask import Flask, request, jsonify, render_template
from datetime import datetime
import uuid
import os

app = Flask(__name__)
DATA_FILE = 'comments.json'  # 存储文件路径

def load_data():
    """从文件加载评论数据"""
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {"comments": []}  # 初始化空数据

def save_data(data):
    """保存评论数据到文件"""
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 加载初始数据
raw_data = load_data()
comments_db = raw_data.get("comments", [])  # 确保从根节点开始

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/api/comments', methods=['GET'])
def get_comments():
    # 只返回顶级评论（非回复）
    top_level = [c for c in comments_db if 'parent_id' not in c]
    return jsonify(top_level)

@app.route('/api/comments', methods=['POST'])
def post_comment():
    data = request.get_json()
    if not data or 'author' not in data or 'content' not in data:
        return jsonify({"error": "Missing required fields"}), 400
    
    new_id = str(uuid.uuid4())
    new_comment = {
        'id': new_id,
        'author': data['author'],
        'content': data['content'],
        'timestamp': datetime.now().isoformat(),
        'likes': 0,
        'replies': []  # 初始化回复数组
    }
    comments_db.append(new_comment)
    save_data({"comments": comments_db})  # &#10071;️ 关键：保存到文件
    return jsonify(new_comment), 201

@app.route('/api/comments/<string:parent_id>/replies', methods=['GET'])
def get_replies(parent_id):
    # 查找指定父评论的回复
    parent_comment = next((c for c in comments_db if c['id'] == parent_id), None)
    if not parent_comment:
        return jsonify({"error": "Parent comment not found"}), 404
    return jsonify(parent_comment['replies'])

@app.route('/api/comments/<string:parent_id>/replies', methods=['POST'])
def post_reply(parent_id):
    # 验证父评论是否存在
    parent_comment = next((c for c in comments_db if c['id'] == parent_id), None)
    if not parent_comment:
        return jsonify({"error": "Parent comment not found"}), 404
    
    data = request.get_json()
    if not data or 'author' not in data or 'content' not in data:
        return jsonify({"error": "Missing required fields"}), 400
    
    reply_id = str(uuid.uuid4())
    reply = {
        'id': reply_id,
        'author': data['author'],
        'content': data['content'],
        'timestamp': datetime.now().isoformat(),
        'likes': 0,
        'replies': []  # 允许多级回复
    }
    parent_comment['replies'].append(reply)
    save_data({"comments": comments_db})  # &#10071;️ 关键：保存到文件
    return jsonify(reply), 201

if __name__ == '__main__':
    app.run(debug=True)
